package net.wsfcp.android.ui.view.main.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import net.wsfcp.android.R;
import net.wsfcp.android.base.BaseActivity;
import net.wsfcp.android.base.BasePresenter;
import net.wsfcp.android.utils.CommonValue;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

//H5页面
public class WebViewActivity extends BaseActivity {
    @BindView(R.id.rl_left)
    RelativeLayout rlLeft;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.btn_right)
    Button btnRight;

    @BindView(R.id.web)
    WebView web;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;


    String url = "http://www.baidu.com";
    String title = "";
    Map<String,String> headerMap=new HashMap<>();//添加请求头区分是否app内调用

    public WebView getWeb() {
        return web;
    }

    public void setUrl(String url) {
        this.url = url;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_web;
    }


    @Override
    protected BasePresenter loadPresenter() {
        return null;
    }

    @Override
    protected void initData() {
        if (!TextUtils.isEmpty(title)) {
            setmTitle(title);
        }
        setLeftClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        headerMap.put(CommonValue.WEBVIEW_HEADER_KEY,CommonValue.WEBVIEW_HEADER_VALUE);
        syncCookie(this,url);
        web.loadUrl(url,headerMap);//加载url


    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected void initView() {
        btnLeft = rlLeft;
        mTitle = txtTitle;
        btRight = btnRight;


        String getUrl = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("mTitle");
        if (!TextUtils.isEmpty(getUrl)) {
            url = getUrl;
        }

        initWeb();
    }

    @SuppressLint("JavascriptInterface")
    public void initWeb() {
        //设置为可调用js方法
        web.getSettings().setJavaScriptEnabled(true);
        web.addJavascriptInterface(new JavaScriptinterface(this, web), CommonValue.JS_METHOD);
        web.setWebViewClient(webViewClient);
        web.setWebChromeClient(new MyWebChrome());
    }


    public class JavaScriptinterface {
        Context context;

        public JavaScriptinterface(Context c, WebView mWebView) {
            context = c;
        }

        /**
         * 与js交互时用到的方法，在js里直接调用的(window.wsfcpJS.getMsg(str))
         */
//        @JavascriptInterface
//        public void getMsg(String str) {
//
//
////            String string = "原生给JS的数据";
////            call = "javascript:showMsg(\"" + string + "\")";
////            mWebView.post(new Runnable() {
////                @Override
////                public void run() {
////
////                    mWebView.loadUrl(call);
////                }
////            });
//
//        }


//        @JavascriptInterface
//        public void openMenu() {
//            getActivity().runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    EventBus.getDefault().post(new OpenMenuEvent());
//                }
//            });
//        }

    }

    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
//            progressBar.setVisibility(View.GONE);

            String webtitle = view.getTitle();
            if (TextUtils.isEmpty(title) && !TextUtils.isEmpty(webtitle)) {
                setmTitle(webtitle);
            }

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
//            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

//不跳转到浏览器
            view.loadUrl(url,headerMap);
            return true;


        }

    };


    private class MyWebChrome extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                progressBar.setProgress(newProgress);//设置进度值
            }
        }
    }


    /**
     * 给WebView同步Cookie
     *
     * @param context 上下文
     * @param url     可以使用[domain][host]
     */
    private void syncCookie(Context context, String url) {

        CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(context);
        }
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(url, CommonValue.WEBVIEW_HEADER_KEY + "=" + CommonValue.WEBVIEW_HEADER_VALUE);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.getInstance().sync();
        } else {
            CookieManager.getInstance().flush();
        }
    }
}
